<template>
  <view class="profile-page">
    <!-- 头像编辑区域 -->
    <view class="avatar-section">
      <view class="avatar-container" @click="changeAvatar">
        <image class="avatar-image" :src="userStore.userAvatar" mode="aspectFill"></image>
        <view class="avatar-overlay">
          <text class="camera-icon">📷</text>
        </view>
      </view>
      <text class="avatar-tip">点击更换头像</text>
    </view>
    
    <!-- 基本信息表单 -->
    <view class="form-section">
      <view class="form-item">
        <text class="form-label">昵称</text>
        <input 
          class="form-input" 
          v-model="formData.nickname" 
          placeholder="请输入昵称"
          maxlength="20"
        />
      </view>
      
      <view class="form-item">
        <text class="form-label">手机号</text>
        <input 
          class="form-input readonly" 
          :value="formatPhone(userStore.userPhone)" 
          readonly
        />
        <text class="change-btn" @click="changePhone">更换</text>
      </view>
      
      <view class="form-item">
        <text class="form-label">性别</text>
        <picker 
          mode="selector" 
          :range="genderOptions" 
          :value="genderIndex"
          @change="onGenderChange"
        >
          <view class="picker-input">
            <text class="picker-text">{{ genderOptions[genderIndex] }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="form-label">生日</text>
        <picker 
          mode="date" 
          :value="formData.birthday" 
          @change="onBirthdayChange"
          :end="maxDate"
        >
          <view class="picker-input">
            <text class="picker-text">{{ formData.birthday || '请选择生日' }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="form-label">邮箱</text>
        <input 
          class="form-input" 
          v-model="formData.email" 
          placeholder="请输入邮箱地址"
          type="email"
        />
      </view>
      
      <view class="form-item">
        <text class="form-label">个人简介</text>
        <textarea 
          class="form-textarea" 
          v-model="formData.bio" 
          placeholder="介绍一下自己吧..."
          maxlength="100"
        ></textarea>
        <text class="char-count">{{ formData.bio.length }}/100</text>
      </view>
    </view>
    
    <!-- 会员信息展示 -->
    <view class="member-info-section">
      <text class="section-title">会员信息</text>
      
      <view class="member-card">
        <view class="member-level" :style="{ backgroundColor: userStore.memberLevelColor }">
          <text class="level-name">{{ userStore.memberLevelName }}</text>
        </view>
        
        <view class="member-stats">
          <view class="stat-item">
            <text class="stat-label">累计消费</text>
            <text class="stat-value">¥{{ formatMoney(userStore.totalSpent) }}</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">累计积分</text>
            <text class="stat-value">{{ userStore.totalPoints }}</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">注册时间</text>
            <text class="stat-value">{{ formatTime(userStore.registerTime, 'YYYY-MM-DD') }}</text>
          </view>
        </view>
        
        <view class="level-progress">
          <text class="progress-label">升级进度</text>
          <view class="progress-bar">
            <view 
              class="progress-fill" 
              :style="{ 
                width: userStore.memberProgress + '%',
                backgroundColor: userStore.memberLevelColor 
              }"
            ></view>
          </view>
          <text class="progress-text">{{ Math.round(userStore.memberProgress) }}%</text>
        </view>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-actions safe-area-inset-bottom">
      <view class="changes-indicator" v-if="hasChanges">
        <text class="changes-text">有未保存的修改</text>
      </view>

      <button
        class="save-btn"
        :disabled="!hasChanges || saving"
        :class="{ disabled: !hasChanges || saving, loading: saving }"
        @click="saveProfile"
      >
        <view v-if="saving" class="loading-icon"></view>
        <text class="btn-text">{{ saving ? '保存中...' : '保存修改' }}</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { formatTime, formatMoney, formatPhone, validateEmail, showError, showSuccess, showLoading, hideLoading } from '@/utils/common'

const userStore = useUserStore()

// 响应式数据
const formData = ref({
  nickname: '',
  gender: 0,
  birthday: '',
  email: '',
  bio: ''
})

const originalData = ref({})
const genderIndex = ref(0)
const saving = ref(false)

// 性别选项
const genderOptions = ['保密', '男', '女']

// 计算属性
const maxDate = computed(() => {
  const today = new Date()
  today.setFullYear(today.getFullYear() - 12) // 最小12岁
  return today.toISOString().split('T')[0]
})

const hasChanges = computed(() => {
  return JSON.stringify(formData.value) !== JSON.stringify(originalData.value)
})

// 方法
const initFormData = () => {
  console.log('初始化表单数据，用户信息:', userStore.userInfo)

  formData.value = {
    nickname: userStore.userName || '',
    gender: userStore.userGender || 0,
    birthday: userStore.userBirthday || '',
    email: userStore.userEmail || '',
    bio: userStore.userBio || ''
  }

  genderIndex.value = formData.value.gender
  originalData.value = JSON.parse(JSON.stringify(formData.value))

  console.log('表单数据初始化完成:', formData.value)
  console.log('原始数据备份:', originalData.value)
}

const changeAvatar = () => {
  uni.showActionSheet({
    itemList: ['从相册选择', '拍照'],
    success: (res) => {
      const sourceType = res.tapIndex === 0 ? ['album'] : ['camera']

      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: sourceType,
        success: (chooseRes) => {
          const tempFilePath = chooseRes.tempFilePaths[0]

          // 显示上传进度
          showLoading('上传中...')

          // 模拟上传过程
          setTimeout(() => {
            try {
              // 模拟上传成功，更新头像
              const success = userStore.updateAvatar(tempFilePath)

              if (success) {
                hideLoading()
                showSuccess('头像更新成功')
              } else {
                hideLoading()
                showError('头像更新失败')
              }
            } catch (error) {
              hideLoading()
              showError('头像更新失败')
            }
          }, 1500)
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
          showError('选择图片失败')
        }
      })
    },
    fail: () => {
      console.log('用户取消选择')
    }
  })
}

const changePhone = () => {
  uni.showModal({
    title: '更换手机号',
    content: '更换手机号功能正在开发中...',
    showCancel: false
  })
}

const onGenderChange = (e) => {
  genderIndex.value = e.detail.value
  formData.value.gender = e.detail.value
}

const onBirthdayChange = (e) => {
  formData.value.birthday = e.detail.value
}

const validateForm = () => {
  if (!formData.value.nickname.trim()) {
    showError('请输入昵称')
    return false
  }
  
  if (formData.value.nickname.length < 2) {
    showError('昵称至少2个字符')
    return false
  }
  
  if (formData.value.email && !validateEmail(formData.value.email)) {
    showError('请输入正确的邮箱地址')
    return false
  }
  
  return true
}

const saveProfile = async () => {
  if (!validateForm()) return

  if (!hasChanges.value) {
    showError('没有修改任何信息')
    return
  }

  saving.value = true
  showLoading('保存中...')

  try {
    console.log('开始保存个人资料:', formData.value)

    // 更新用户信息
    const updateData = {
      userName: formData.value.nickname.trim(),
      userGender: parseInt(formData.value.gender),
      userBirthday: formData.value.birthday,
      userEmail: formData.value.email.trim(),
      userBio: formData.value.bio.trim()
    }

    console.log('准备更新的数据:', updateData)

    const result = await userStore.updateProfile(updateData)

    if (result.success) {
      // 更新原始数据，标记为已保存
      originalData.value = JSON.parse(JSON.stringify(formData.value))

      hideLoading()
      showSuccess('保存成功')

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      hideLoading()
      showError(result.message || '保存失败')
    }
  } catch (error) {
    console.error('保存个人资料失败:', error)
    hideLoading()
    showError('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 生命周期
onMounted(() => {
  if (!userStore.isLoggedIn) {
    uni.showModal({
      title: '请先登录',
      content: '编辑个人资料需要先登录账户',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        } else {
          uni.navigateBack()
        }
      }
    })
    return
  }
  
  initFormData()
})
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background: var(--color-background);
  padding: 16px;
  padding-bottom: 100px;
}

// 头像编辑区域
.avatar-section {
  text-align: center;
  padding: 32px 0;
  background: white;
  border-radius: var(--radius-xl);
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
}

.avatar-container {
  position: relative;
  width: 100px;
  height: 100px;
  margin: 0 auto 12px;
  border-radius: 50px;
  overflow: hidden;
  transition: all var(--transition-normal);

  &:active {
    transform: scale(0.95);
  }
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 50px;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity var(--transition-normal);

  .avatar-container:active & {
    opacity: 1;
  }
}

.camera-icon {
  font-size: 24px;
  color: white;
}

.avatar-tip {
  font-size: 14px;
  color: var(--color-text-secondary);
}

// 表单区域
.form-section {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
}

.form-item {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid var(--color-border);
  position: relative;

  &:last-child {
    border-bottom: none;
  }

  &:has(.form-textarea) {
    align-items: flex-start;
    flex-direction: column;
    gap: 8px;
  }
}

.form-label {
  font-size: 16px;
  color: var(--color-text-primary);
  font-weight: 500;
  min-width: 80px;
  margin-right: 16px;
}

.form-input {
  flex: 1;
  font-size: 16px;
  color: var(--color-text-primary);
  border: none;
  outline: none;
  background: transparent;

  &.readonly {
    color: var(--color-text-secondary);
  }

  &::placeholder {
    color: var(--color-text-tertiary);
  }
}

.form-textarea {
  width: 100%;
  min-height: 80px;
  font-size: 16px;
  color: var(--color-text-primary);
  border: none;
  outline: none;
  background: var(--color-background);
  border-radius: var(--radius-md);
  padding: 12px;
  resize: none;

  &::placeholder {
    color: var(--color-text-tertiary);
  }
}

.char-count {
  font-size: 12px;
  color: var(--color-text-tertiary);
  align-self: flex-end;
  margin-top: 4px;
}

.change-btn {
  font-size: 14px;
  color: var(--color-primary);
  padding: 4px 8px;
  border-radius: var(--radius-sm);
  transition: all var(--transition-normal);

  &:active {
    background: rgba(0, 122, 255, 0.1);
  }
}

.picker-input {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.picker-text {
  font-size: 16px;
  color: var(--color-text-primary);
}

.picker-arrow {
  font-size: 14px;
  color: var(--color-text-tertiary);
}

// 会员信息区域
.member-info-section {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
  margin-bottom: 16px;
  display: block;
}

.member-card {
  background: linear-gradient(135deg, var(--color-premium), var(--color-primary));
  border-radius: var(--radius-lg);
  padding: 20px;
  color: white;
}

.member-level {
  display: inline-block;
  padding: 6px 16px;
  border-radius: var(--radius-xl);
  background: rgba(255, 255, 255, 0.2);
  margin-bottom: 16px;
}

.level-name {
  font-size: 14px;
  font-weight: 600;
  color: white;
}

.member-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  display: block;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: white;
}

.level-progress {
  display: flex;
  align-items: center;
  gap: 12px;
}

.progress-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  min-width: 60px;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 3px;
  transition: width var(--transition-normal);
}

.progress-text {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  min-width: 35px;
  text-align: right;
}

// 底部操作栏
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  border-top: 1px solid var(--color-border);
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
  z-index: 1000;
}

.changes-indicator {
  flex: 1;
}

.changes-text {
  font-size: 14px;
  color: var(--color-warning);
  font-weight: 500;
}

.save-btn {
  min-width: 120px;
  height: 44px;
  background: linear-gradient(135deg, var(--color-primary), var(--color-primary-light));
  color: white;
  border: none;
  border-radius: var(--radius-xl);
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  box-shadow: 0 4px 16px rgba(0, 122, 255, 0.3);
  transition: all var(--transition-normal);

  &:not(.disabled):active {
    transform: scale(0.95);
  }

  &.disabled {
    background: var(--color-text-tertiary);
    box-shadow: none;
  }
}

.loading-icon {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.btn-text {
  color: white;
}

// 响应式适配
@media (max-width: 375px) {
  .profile-page {
    padding: 12px;
  }

  .avatar-container {
    width: 80px;
    height: 80px;
    border-radius: 40px;
  }

  .avatar-image {
    border-radius: 40px;
  }

  .form-section,
  .member-info-section {
    padding: 16px;
  }

  .form-item {
    padding: 12px 0;
  }

  .form-label {
    min-width: 70px;
    font-size: 15px;
  }

  .form-input,
  .picker-text {
    font-size: 15px;
  }

  .member-stats {
    grid-template-columns: 1fr;
    gap: 12px;
    text-align: left;
  }

  .stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .stat-label {
    margin-bottom: 0;
  }
}
</style>
